import axios from 'axios'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const baseURL = import.meta.env.VITE_BASE_URL
const router = useRouter();

const instance = axios.create({
  baseURL,
  timeout: 30000,
})

const igonreMsgPath = new Set(
)

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 携带token
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  (err) => Promise.reject(err),
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
      if (!igonreMsgPath.has(res.config.url)) {
        ElMessage.success(res.data?.msg || '操作成功')
      }

    return res
  },
  (err) => {
    switch (err.status) {
      case 401: {
        const userStore = useUserStore();
        userStore.removeToken();
        router.push('/login');
        break;
      }
      case 500: {
        ElMessage.error("服务器异常！");
        return Promise.reject(err);
      }
    }
    ElMessage.error(err.response?.data.msg || '网络异常！');
    return Promise.reject(err)
  },
)

export default instance
export { baseURL }
